#include "feedbackwidget.h"
#include "ui_feedbackwidget.h"
#include "databasemanager.h"
#include "session.h"
#include <QSqlQuery>
#include <QMessageBox>
#include <QDebug>
#include <QSqlError>
#include <QHeaderView>

feedbackwidget::feedbackwidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::feedbackwidget)
{
    ui->setupUi(this);

    loadUserVisits();
    loadLatestFeedbacks();

    ui->spinBoxRating->setRange(0, 5); // 设置评分范围
}

feedbackwidget::~feedbackwidget()
{
    delete ui;
    delete visitModel;
}

void feedbackwidget::loadUserVisits()
{
    int visitorId = Session::getVisitorId();
    if (visitorId < 0) {
        QMessageBox::warning(this, "错误", "未登录，无法加载预约记录");
        return;
    }

    QSqlDatabase db = DatabaseManager::instance().getDatabase();
    if (!db.isOpen()) {
        QMessageBox::warning(this, "错误", "数据库未连接");
        return;
    }

    if (visitModel) {
        delete visitModel;
        visitModel = nullptr;
    }

    visitModel = new QSqlQueryModel(this);

    QString sql = QString(
        "SELECT vv.visit_id AS '预约ID', "
        "ee.name AS '活动名称', "
        "vv.visit_date AS '预约日期', "
        "vv.satisfaction_rating AS '评分', "
        "vv.feedback AS '反馈内容' "
        "FROM Venue_Visits vv "
        "LEFT JOIN Exhibitions_Events ee ON vv.event_id = ee.event_id "
        "WHERE vv.visitor_id = %1 "
        "ORDER BY vv.visit_date DESC"
    ).arg(visitorId);

    visitModel->setQuery(sql, db);

    if (visitModel->lastError().isValid()) {
        QMessageBox::warning(this, "查询错误", visitModel->lastError().text());
        return;
    }

    ui->tableViewVisits->setModel(visitModel);
    ui->tableViewVisits->setColumnHidden(0, true); // 隐藏预约ID
    ui->tableViewVisits->horizontalHeader()->setStretchLastSection(true);
    ui->tableViewVisits->resizeColumnsToContents();
}

void feedbackwidget::on_tableViewVisits_clicked(const QModelIndex &index)
{
    if (!index.isValid())
        return;

    QModelIndex visitIdIndex = visitModel->index(index.row(), 0); // 第一列是 visit_id
    currentVisitId = visitModel->data(visitIdIndex).toInt();

    QSqlDatabase db = DatabaseManager::instance().getDatabase();
    QSqlQuery query(db);
    query.prepare("SELECT satisfaction_rating, feedback FROM Venue_Visits WHERE visit_id = :vid");
    query.bindValue(":vid", currentVisitId);
    if (query.exec() && query.next()) {
        int rating = query.value(0).toInt();
        QString feedback = query.value(1).toString();

        ui->spinBoxRating->setValue(rating);
        ui->textEditFeedback->setPlainText(feedback);
    }
}

void feedbackwidget::on_pushButtonSubmit_clicked()
{
    if (currentVisitId < 0) {
        QMessageBox::warning(this, "错误", "请先选择一个预约活动");
        return;
    }

    int rating = ui->spinBoxRating->value();
    QString feedback = ui->textEditFeedback->toPlainText();

    QSqlDatabase db = DatabaseManager::instance().getDatabase();
    if (!db.isOpen()) {
        QMessageBox::warning(this, "错误", "数据库未连接");
        return;
    }

    QSqlQuery query(db);
    query.prepare("UPDATE Venue_Visits SET satisfaction_rating = :rating, feedback = :feedback WHERE visit_id = :vid");
    query.bindValue(":rating", rating);
    query.bindValue(":feedback", feedback);
    query.bindValue(":vid", currentVisitId);

    if (!query.exec()) {
        QMessageBox::warning(this, "提交失败", query.lastError().text());
        return;
    }

    QMessageBox::information(this, "提交成功", "评价提交成功，谢谢您的反馈！");
    loadUserVisits();
    loadLatestFeedbacks(); // 更新场馆评价表
}

void feedbackwidget::loadLatestFeedbacks()
{
    QSqlQueryModel *model = new QSqlQueryModel(this);

    QString sql = R"(
        SELECT
            v.name AS 场馆名称,
            vv.feedback AS 评价内容,
            vv.satisfaction_rating AS 星级
        FROM
            Venue_Visits vv
        JOIN
            Venues v ON vv.venue_id = v.venue_id
        JOIN (
            SELECT venue_id, MAX(visit_id) AS max_visit_id
            FROM Venue_Visits
            WHERE feedback IS NOT NULL AND feedback != ''
            GROUP BY venue_id
        ) latest ON vv.venue_id = latest.venue_id AND vv.visit_id = latest.max_visit_id
        ORDER BY vv.visit_id DESC
    )";

    model->setQuery(sql, DatabaseManager::instance().getDatabase());

    if (model->lastError().isValid()) {
        qDebug() << "查询反馈失败:" << model->lastError().text();
        return;
    }

    qDebug() << "反馈记录行数：" << model->rowCount();

    ui->tableViewFeedbacks->setModel(model);
    ui->tableViewFeedbacks->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableViewFeedbacks->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableViewFeedbacks->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableViewFeedbacks->horizontalHeader()->setStretchLastSection(true);
    ui->tableViewFeedbacks->resizeColumnsToContents();
}
